﻿using NewRen.Models.ViewModel;
using NewRen.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Security;
using NewRen.Schemas;
using System.Web.Hosting;
using System.IO;
using NewRen.Models.DataModel;
using NewRen.Helpers;
using System.Data.Entity;
using System.Data.Entity.Core.Objects;
using NewRen.Log4net;

namespace NewRen.Controllers
{
    public class BbsController : BaseController
    {
        // GET: Bbs
        /// <summary>
        /// 论坛首页
        /// </summary>
        /// <param name="theme_nav"></param>
        /// <param name="p"></param>
        /// <returns></returns>
        [HttpGet]
        public ActionResult Index(int theme_nav = 1, int p = 0)
        {
            try
            {
                var index = 25;
                var today = DateTime.Now;
                var yesterday = DateTime.Now.AddDays(-1);
                var this_week = DateTime.Now.AddDays(-7);
                IEnumerable<Topic> query = db.Topics.Where(x => x.IsShow == true).Where(x => x.IsColse == false).AsEnumerable();
                //热门主题
                var hotspot = db.Database.SqlQuery<Topic>("select Top 5 * from Topics as t where IsShow=1 and IsColse=0 order by (Browses+(select COUNT(*) from Replies as r where t.ID=r.TopicID)) desc");
                //推荐（显示置顶和官方认证贴，按浏览量排序）
                var hot_topic = query.OrderByDescending(c => c.Browses).Where(x => x.Top == true || x.IsOfficeIdentified == true).AsEnumerable();
                //最新（显示一周内所有的贴，按时间排序）
                var new_topic = query.OrderByDescending(x => x.Time).Where(x => x.Time > this_week).AsEnumerable();
                if (theme_nav == 1)
                {
                    query = hot_topic;
                }
                else if (theme_nav == 2)
                {
                    query = new_topic;
                }
                else
                {
                    theme_nav = 1;
                    ViewBag.ThemeNav = 1;
                    query = hot_topic;
                }
                //最新数
                ViewBag.TopicsNewNum = new_topic.Count();
                //推荐数
                ViewBag.TopicsHotNum = hot_topic.Count();
                //昨日发帖数
                ViewBag.TopicYesterDayNum = db.Topics.Where(x => x.Time.Year == yesterday.Year && x.Time.Month == yesterday.Month && x.Time.Day == yesterday.Day).Count();
                //今日发帖数
                ViewBag.TopicToDayNum = db.Topics.Where(x => x.Time.Year == today.Year && x.Time.Month == today.Month && x.Time.Day == today.Day).Count();
                //总发帖数
                ViewBag.TopicsNum = db.Topics.Where(x => x.IsShow == true).Count();
                //总用户数
                ViewBag.UserNum = db.Users.Count();
                //版块推荐(按板块浏览量+板块贴数量排名，输出前10个)
                ViewBag.NewForums = db.Database.SqlQuery<Plate>("select * from Plates where IsColse=0  and ID in (select top 10 Topics.PlateID from Topics where IsShow=1 group by PlateID) order by Browses DESC");
                //板块列表
                ViewBag.ForumList = db.Plates.Where(x => x.IsColse == false).Take(7).ToList();
                //热门版块(按板块浏览量排名，输出前5个)
                ViewBag.HotForums = db.Plates.OrderByDescending(x => x.Browses).Where(x => x.IsColse
     == false).Take(5).ToList();
                //最新和推荐当前状态
                ViewBag.ThemeNav = theme_nav;
                //热门主题
                ViewBag.HotsPot = hotspot;
                //推荐关注
                var collect = db.Database.SqlQuery<Plate>("select * from Plates where ID in (select Top 5 TID from Collects where CollectTypeAsInt=2 group by TID) and IsColse=0");
                ViewBag.Collect = collect;
                query = query.OrderByDescending(x => x.Top);
                ViewBag.PageInfo = PagerHelper.Do(ref query, index, p);
                return View(query);
            }
            catch (Exception ex)
            {
                log.Error(new LogContent("论坛首页出错", Helpers.HttpHelper.GetIPAddress()), ex);
                return Redirect("/Shared/Info?msg=数据异常，请稍后重试");
            }
        }

        /// <summary>
        /// 显示主题
        /// </summary>
        /// <param name="id"></param>
        /// <param name="p"></param>
        /// <returns></returns>
        [HttpGet]
        public ActionResult Show(int id, int p = 0)
        {
            User user = new User();
            Topic topic = new Topic();
            topic = db.Topics.Find(id);
            if(topic!=null)
            {
                if (topic.IsShow)
                {
                    try
                    {
                        topic.Browses = topic.Browses + 1;
                        db.SaveChanges();
                        ViewBag.topic = topic;
                        user = db.Users.Where(u => u.ID == topic.UserID).SingleOrDefault();
                        List<Topic> topics = new List<Topic>();
                        topics = db.Topics.Where(t => t.UserID == user.ID).ToList();
                        ViewBag.utopiccount = topics.Count();
                        var count = topic.Replies.Count();
                        ViewBag.topics = topics;
                        ViewBag.user = user;
                        ViewBag.count = count;
                        List<vReply> replies = new List<vReply>();
                        IEnumerable<Reply> query = topic.Replies.OrderByDescending(t => t.Time).Where(t => t.FatherID == null).AsEnumerable();
                        ViewBag.PageInfo = PagerHelper.Do(ref query, 5, p);
                        foreach (var item in query)
                        {
                            replies.Add(new vReply(item));
                        }
                        if (CurrentUser == null)
                        {
                            ViewBag.IsCollected = false;
                        }
                        else
                        {
                            var collect = db.Collects.Where(c => c.CollectTypeAsInt == 2 && c.TID == topic.PlateID && c.UserID == CurrentUser.ID).FirstOrDefault();
                            if (collect == null)
                            {
                                ViewBag.IsCollected = false;
                            }
                            else
                            {
                                ViewBag.IsCollected = true;
                            }
                        }
                        ViewBag.Plate = db.Plates.Find(topic.PlateID);
                        ViewBag.Collections = db.Collects.Where(c => c.CollectTypeAsInt == 2 && c.TID == topic.PlateID).Count();
                        return View(replies);
                    }
                    catch (Exception ex)
                    {
                        log.Error(new LogContent("显示主题出错", Helpers.HttpHelper.GetIPAddress()), ex);
                        return Redirect("/Shared/Info?msg=主题不存在，请不要不合理操作");
                    }
                }
                else
                {
                    return Redirect("/Shared/Info?msg=主题已关闭,请不要不合理操作");
                }
            }
            else
            {
                return Redirect("/Shared/Info?msg=主题不存在，请不要不合理操作");
            }
        }

        #region 增加主题
        /// <summary>
        /// 增加主题页面
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpGet]
        public ActionResult Add(int id = 0)
        {
            Plate plate = new Plate();
            List<Plate> platelist = new List<Plate>();
            platelist = (from pl in db.Plates where pl.IsColse == false select pl).ToList();
            ViewBag.platelist = platelist;
            if (id == 0)
            {
                ViewBag.ptitle = null;
            }
            else
            {
                plate = (from p in db.Plates where p.ID == id select p).FirstOrDefault();
                ViewBag.ptitle = plate.Title;
            }
            ViewBag.plateID = id;
            return View();
        }

        /// <summary>
        /// 增加主题
        /// </summary>
        /// <param name="title"></param>
        /// <param name="classify"></param>
        /// <param name="content"></param>
        /// <returns></returns>
        [ValidateAntiForgeryToken]
        [HttpPost]
        [ValidateInput(false)]  //允许特殊字符提交/
        public ActionResult Add(string title, int classify, string content)
        {
            List<Plate> platelist = new List<Plate>();
            platelist = (from p in db.Plates where p.IsColse == false select p).ToList();
            ViewBag.platelist = platelist;
            if (ModelState.IsValid)
            {
                try
                {
                    User user = new User();
                    db.Users.Find(CurrentUser.ID);
                    user.Integration += 20;

                    IntegrationRecord integration = new IntegrationRecord();
                    integration.Hint = "发布帖子送积分";
                    integration.Integration = 20;
                    integration.Time = DateTime.Now;
                    integration.UserID = CurrentUser.ID;
                    db.IntegrationRecords.Add(integration);
                    db.SaveChanges();

                    Topic topic = new Topic();
                    topic.Title = title;
                    topic.Content = content;
                    topic.Top = false;
                    topic.Time = DateTime.Now;
                    topic.PlateID = classify;
                    topic.UserID = CurrentUser.ID;
                    topic.Report = 0;
                    topic.Reward = 5;
                    topic.Browses = 0;
                    topic.IsOfficeIdentified = false;
                    topic.IsShow = true;
                    db.Topics.Add(topic);
                    db.SaveChanges();
                    return Redirect("/Bbs/Index");
                }
                catch (Exception ex)
                {
                    ModelState.AddModelError("", "数据异常，请审核后重新提交");
                    log.Error(new LogContent("增加主题失败", Helpers.HttpHelper.GetIPAddress()), ex);
                }
            }
            else
            {
                ModelState.AddModelError("", "信息不全，请审核后提交");
            }
            ViewBag.platelist = db.Plates.Where(x => x.IsColse == false).ToList();
            return View();
        }

        #endregion
        /// <summary>
        /// 回复
        /// </summary>
        /// <param name="content"></param>
        /// <param name="cid"></param>
        /// <param name="id"></param>
        /// <param name="fatherID"></param>
        /// <returns></returns>
        [HttpPost]
        [ValidateInput(false)]  //允许特殊字符提交/
        public ActionResult ReplyAdd(string content, int cid, int id, int? fatherID)
        {


            AjaxModel ajaxModel = new AjaxModel();
            Reply reply = new Reply();
            try
            {
                reply.Content = content;
                reply.TopicID = id;
                Topic topic = db.Topics.Find(id);
                reply.Time = DateTime.Now;
                reply.UserID = cid;
                reply.FatherID = fatherID;
                db.Replies.Add(reply);
                topic.LastReply = DateTime.Now;
                db.SaveChanges();
                ajaxModel.Data = new vReply(reply);
                ajaxModel.Statu = "ok";
                ajaxModel.Msg = "获取成功";
            }
            catch (Exception ex)
            {
                ajaxModel.Statu = "err";
                ajaxModel.Msg = "获取失败";
                log.Error(new LogContent("增加回复失败", Helpers.HttpHelper.GetIPAddress()), ex);
            }
            return Json(ajaxModel, JsonRequestBehavior.AllowGet);
        }

        /// <summary>
        /// 板块显示
        /// </summary>
        /// <param name="id"></param>
        /// <param name="Time"></param>
        /// <param name="Publish"></param>
        /// <param name="Rule"></param>
        /// <param name="p"></param>
        /// <returns></returns>
        [HttpGet]
        public ActionResult Forum(int id, int Time = 0, string Publish = "", int Rule = 0, int p = 0)
        {
            Plate plate = db.Plates.Find(id);
            if(plate!=null)
            {
                if (plate.IsColse == false)
                {
                    try
                    {
                        plate.Browses = plate.Browses + 1;
                        db.SaveChanges();
                        var index = 25;
                        var today = Convert.ToDateTime(DateTime.Now.ToString("yyyy-MM-dd"));
                        var yesterday = Convert.ToDateTime(DateTime.Now.AddDays(-1).ToString("yyyy-MM-dd"));
                        var day_before_yesterday = Convert.ToDateTime(DateTime.Now.AddDays(-2).ToString("yyyy-MM-dd"));
                        var this_week = DateTime.Now.AddDays(-7);
                        //昨日发帖数
                        ViewBag.PlatesYesterDayNum = db.Topics.Where(x => x.PlateID == id).Where(x => x.IsShow == true).Where(x => x.Time < today).Where(x => x.Time > yesterday).Count();
                        //今日发帖数
                        ViewBag.PlatesToDayNum = db.Topics.Where(x => x.PlateID == id).Where(x => x.IsShow == true).Where(x => x.Time > today).Count();
                        //板块发帖数
                        ViewBag.PlatesNum = db.Topics.Where(x => x.PlateID == id).Where(x => x.IsShow == true).Count();
                        //总发帖数
                        ViewBag.TopicsNum = db.Topics.Where(x => x.IsShow == true).Count();
                        //版块推荐
                        ViewBag.NewForums = db.Database.SqlQuery<Plate>("select * from Plates where ID in (select top 10 Topics.PlateID from Topics where IsShow=1 group by PlateID) order by Browses DESC");
                        //板块信息
                        ViewBag.Plate = db.Plates.Find(id);
                        //过滤
                        IEnumerable<Topic> query = db.Topics.AsEnumerable();
                        ViewBag.DownTime = "全部时间";
                        if (Rule == 1)
                        {
                            query = query.Where(x => x.Top == true).Where(x => x.IsOfficeIdentified == true);
                        }
                        else if (Rule == 2)
                        {
                            Rule = 2;
                        }
                        else
                        {
                            Rule = 0;
                        }
                        ViewBag.Rule = Rule;
                        if (Time != 0)
                        {
                            var time = Convert.ToDateTime(DateTime.Now.AddDays(-Time).ToShortDateString());
                            query = query.Where(x => x.Time > time);
                            if (Time == 1)
                            {
                                ViewBag.DownTime = "一天";
                            }
                            else if (Time == 2)
                            {
                                ViewBag.DownTime = "两天";
                            }
                            else if (Time == 7)
                            {
                                ViewBag.DownTime = "一周";
                            }
                            else if (Time == 31)
                            {
                                ViewBag.DownTime = "一个月";
                            }
                            else if (Time == 92)
                            {
                                ViewBag.DownTime = "两个月";
                            }
                        }
                        ViewBag.DownPublish = "默认排序";
                        if (!string.IsNullOrEmpty(Publish))
                        {
                            if (Publish == "Time")
                            {
                                query = query.OrderByDescending(x => x.Time);
                                ViewBag.DownPublish = "发帖时间";
                            }
                            else if (Publish == "Browse")
                            {
                                query = query.OrderByDescending(x => x.Browses);
                                ViewBag.DownPublish = "浏览数";
                            }
                            else if (Publish == "Replies")
                            {
                                query = query.OrderByDescending(x => x.Replies.Count);
                                ViewBag.DownPublish = "回复数";
                            }
                        }
                        ViewBag.DownTimeSelect = Time;
                        ViewBag.DownPublshSelect = Publish;
                        ViewBag.Page = p;
                        query = query.Where(x => x.PlateID == id).Where(x => x.IsShow == true).OrderByDescending(x => x.Top).AsEnumerable();
                        //板块列表
                        ViewBag.ForumList = db.Plates.Where(x => x.IsColse == false).Take(7).ToList();
                        //版主（板块内发帖数最多人）
                        PlateOwner find_user = db.PlateOwners.Where(x=>x.PlateID==id).FirstOrDefault();
                        if (find_user != null)
                        {
                            ViewBag.User = db.Users.Find(find_user.UserID);
                        }
                        else
                        {
                            ViewBag.User = null;
                        }
                        //关注
                        ViewBag.Collections = db.Collects.Where(c => c.CollectTypeAsInt == 2 && c.TID == id).Count();
                        ViewBag.PageInfo = PagerHelper.Do(ref query, index, p);
                        return View(query);
                    }
                    catch (Exception ex)
                    {
                        log.Error(new LogContent("论坛首页出错", Helpers.HttpHelper.GetIPAddress()), ex);
                        return Redirect("/Shared/Info?msg=板块不存在，请不要不合理操作");
                    }
                }
                else
                {
                    return Redirect("/Shared/Info?msg=板块已关闭，请不要不合理操作");
                }
            }
            else
            {
                return Redirect("/Shared/Info?msg=板块不存在，请不要不合理操作");
            }
        }


        /// <summary>
        /// 签到
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        [Authorize]
        [ValidateSID]
        public ActionResult Sign()
        {
            AjaxModel ajaxModel = new AjaxModel();
            var now = DateTime.Now;
            var yesterday = now.AddDays(-1);
            var sign = db.ForumSigns.Where(s => s.Time.Year == now.Year && s.Time.Month == now.Month && s.Time.Day == now.Day && s.UserID == CurrentUser.ID).FirstOrDefault();
            if (sign == null)
            {
                try
                {
                    sign = new ForumSign();
                    sign.UserID = CurrentUser.ID;
                    sign.Time = DateTime.Now;
                    db.ForumSigns.Add(sign);

                    var record = new SignRecord();
                    record = db.SignRecords.Where(sr => sr.UserID == CurrentUser.ID).FirstOrDefault();
                    if (record == null)
                    {
                        record = new SignRecord();
                        record.UserID = CurrentUser.ID;
                        record.Days = 1;
                        db.SignRecords.Add(record);
                    }
                    else
                    {
                        var _sign = db.ForumSigns.Where(s => s.Time.Year == yesterday.Year && s.Time.Month == yesterday.Month && s.Time.Day == yesterday.Day).FirstOrDefault();
                        if (_sign == null)
                        {
                            record.Days = 1;
                        }
                        else
                        {
                            record.Days = record.Days + 1;
                        }
                    }

                    db.SaveChanges();
                    ajaxModel.Statu = "ok";
                    ajaxModel.Msg = "签到成功！";
                }
                catch (Exception ex)
                {
                    ajaxModel.Statu = "err";
                    ajaxModel.Msg = "签到失败！";
                    log.Error(new LogContent("签到出错", Helpers.HttpHelper.GetIPAddress()), ex);
                }
            }
            else
            {
                ajaxModel.Statu = "err";
                ajaxModel.Msg = "今天已经签过";
            }
            return Json(ajaxModel);
        }

        /// <summary>
        /// 签到信息
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ActionResult SignInfo()
        {
            AjaxModel ajaxModel = new AjaxModel();
            var now = DateTime.Now;
            int[] a = new int[3];
            try
            {
                //签到人数
                var sign_people = db.ForumSigns.Where(s => s.Time.Year == now.Year && s.Time.Month == now.Month && s.Time.Day == now.Day).Count();
                a[0] = sign_people;
                if (CurrentUser != null)
                {
                    //签到天数
                    var record = db.SignRecords.Where(r => r.UserID == CurrentUser.ID).FirstOrDefault();
                    a[1] = record.Days;
                    a[2] = db.SignRecords.Where(r => r.Days >= record.Days).Count();
                    ajaxModel.Statu = "ok";
                    ajaxModel.Msg = "查找成功";
                    ajaxModel.Data = a;
                }
                else
                {
                    ajaxModel.Statu = "only_num";
                    ajaxModel.Msg = "查找成功";
                    ajaxModel.Data = a[0];
                }
            }
            catch (Exception ex)
            {
                ajaxModel.Statu = "err";
                ajaxModel.Msg = "数据异常";
                log.Error(new LogContent("签到数据异常", Helpers.HttpHelper.GetIPAddress()), ex);
            }
            return Json(ajaxModel);
        }

        /// <summary>
        /// 举报
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        [Authorize]
        [ValidateSID]
        public ActionResult Report(int id)
        {
            AjaxModel ajaxModel = new AjaxModel();
            Topic topic = db.Topics.Find(id);
            if (topic != null)
            {
                try
                {
                    topic.Report = topic.Report + 1;
                    db.SaveChanges();
                    ajaxModel.Statu = "ok";
                    ajaxModel.Msg = "举报成功！";
                }
                catch (Exception ex)
                {
                    ajaxModel.Statu = "err";
                    ajaxModel.Msg = "举报失败！";
                    log.Error(new LogContent("举报出错", Helpers.HttpHelper.GetIPAddress()), ex);
                }
            }
            else
            {
                ajaxModel.Statu = "err";
                ajaxModel.Msg = "非法错误！";
            }
            return Json(ajaxModel);
        }

        /// <summary>
        /// 显示图片
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpGet]
        public ActionResult ShowForumPicture(int id)
        {
            try
            {
                var forum = db.Plates.Find(id);
                forum = db.Plates.Find(id);
                return File(forum.Picture, "image/jpg");
            }
            catch (Exception ex)
            {
                log.Error(new LogContent("板块图片异常", Helpers.HttpHelper.GetIPAddress()), ex);
                return File("/Imges/userphoto.png", "image/jpg");
            }
        }


        /// <summary>
        ///  添加收藏
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        [ValidateSID]
        public ActionResult CollectForum(int id)
        {
            AjaxModel ajaxModel = new AjaxModel();
            if (CurrentUser == null)
            {
                ajaxModel.Statu = "err";
                ajaxModel.Msg = "请先登录";
            }
            else
            {
                try
                {
                    var collect = new Collect();
                    collect = db.Collects.Where(c => c.CollectTypeAsInt == 2 && c.TID == id && c.UserID == CurrentUser.ID).FirstOrDefault();
                    if (collect == null)
                    {
                        collect = new Collect();
                        collect.Time = DateTime.Now;
                        collect.TID = id;
                        collect.UserID = CurrentUser.ID;
                        collect.CollectTypeAsInt = 2;
                        db.Collects.Add(collect);
                        db.SaveChanges();
                        ajaxModel.Statu = "ok";
                        ajaxModel.Msg = "关注成功";
                    }
                    else
                    {
                        ajaxModel.Statu = "err";
                        ajaxModel.Msg = "已关注";
                    }
                }
                catch (Exception ex)
                {
                    ajaxModel.Statu = "err";
                    ajaxModel.Msg = "关注出错";
                    log.Error(new LogContent("关注出错", Helpers.HttpHelper.GetIPAddress()), ex);
                }
            }
            return Json(ajaxModel);
        }
        [HttpPost]
        [ValidateSID]
        public ActionResult CancelCollectForum(int id)
        {
            AjaxModel ajaxModel = new AjaxModel();
            try
            {
                var collect = new Collect();
                collect = db.Collects.Where(c => c.CollectTypeAsInt == 2 && c.TID == id && c.UserID == CurrentUser.ID).FirstOrDefault();
                if (collect != null)
                {
                    db.Collects.Remove(collect);
                    db.SaveChanges();
                    ajaxModel.Statu = "ok";
                    ajaxModel.Msg = "取消关注成功";
                }
                else
                {
                    ajaxModel.Statu = "err";
                    ajaxModel.Msg = "未关注";
                }
            }
            catch (Exception ex)
            {
                ajaxModel.Statu = "err";
                ajaxModel.Msg = "取消关注出错";
                log.Error(new LogContent("取消关注出错", Helpers.HttpHelper.GetIPAddress()), ex);
            }
            return Json(ajaxModel);
        }

        [HttpPost]
        [ValidateSID]
        public ActionResult CollectShow(int id)
        {
            AjaxModel ajaxModel = new AjaxModel();
            if (CurrentUser == null)
            {
                ajaxModel.Statu = "err";
                ajaxModel.Msg = "请先登录";
            }
            else
            {
                try
                {
                    var collect = new Collect();
                    collect = db.Collects.Where(c => c.CollectTypeAsInt == 2 && c.TID == id && c.UserID == CurrentUser.ID).FirstOrDefault();
                    if (collect == null)
                    {
                        collect = new Collect();
                        collect.Time = DateTime.Now;
                        collect.TID = id;
                        collect.UserID = CurrentUser.ID;
                        collect.CollectTypeAsInt = 2;
                        db.Collects.Add(collect);
                        db.SaveChanges();
                        ajaxModel.Statu = "ok";
                        ajaxModel.Msg = "关注成功";
                    }
                    else
                    {
                        ajaxModel.Statu = "err";
                        ajaxModel.Msg = "已关注";
                    }
                }
                catch (Exception ex)
                {
                    ajaxModel.Statu = "err";
                    ajaxModel.Msg = "关注出错";
                    log.Error(new LogContent("关注出错", Helpers.HttpHelper.GetIPAddress()), ex);
                }
            }
            return Json(ajaxModel);
        }
        /// <summary>
        /// 板块列表展示页面
        /// </summary>
        /// <returns></returns>
        public ActionResult PlateList()
        {
            try
            {
                var query = db.Plates.Where(x => x.IsColse == false).ToList();
                List<vPlate> PlateList = new List<vPlate>();
                foreach (Plate item in query)
                {
                    vPlate vplate = new vPlate(item);
                    PlateList.Add(vplate);
                }
                ViewBag.Plates = PlateList;
                return View();
            }
            catch (Exception ex)
            {
                log.Error(new LogContent("关注出错", Helpers.HttpHelper.GetIPAddress()), ex);
                return Redirect("/Shared/Info?msg=板块不存在，请不要不合理操作");
            }
        }
    }
}